package cn.ihelloworld.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.ihelloworld.bean.SysUser;
import cn.ihelloworld.dao.ISysUserDao;
import cn.ihelloworld.dao.Pagation;

@Repository
public class SysUserDaoImpl implements ISysUserDao{
	
	@Autowired
	private SessionFactory sf;

	@Override
	public SysUser get(String id) {
		return (SysUser)sf.getCurrentSession().get(SysUser.class,id);
	}

	@Override
	public List<SysUser> select(SysUser t) {
		List<SysUser> list=new ArrayList<SysUser>();
		if(t!=null){
			Criteria criteria=sf.getCurrentSession().createCriteria(SysUser.class);
			if(t.getAccount()!=null){
				criteria.add(Restrictions.eq("account", t.getAccount()));
			}
			if(t.getPassword()!=null){
				criteria.add(Restrictions.eq("password", t.getPassword()));
			}
			list=criteria.list();
		}
		return list;
	}

	@Override
	public Pagation<SysUser> selectForPage(SysUser t,int currentPage,int pageSize) {
		Pagation<SysUser> pagation=new Pagation<SysUser>();
		int start=currentPage==0?0:(currentPage-1)*pageSize;
		int end=currentPage*pageSize;
		pagation.setStart(start);
		pagation.setEnd(end);
		List<SysUser> list=new ArrayList<SysUser>();
		if(t!=null){
			Criteria criteria=sf.getCurrentSession().createCriteria(SysUser.class);
			if(t.getAccount()!=null){
				criteria.add(Restrictions.eq("account", t.getAccount()));
			}
			if(t.getPassword()!=null){
				criteria.add(Restrictions.eq("password", t.getPassword()));
			}
			Integer count=(Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			pagation.setTotal(count);
			criteria.setProjection(null);
			criteria.setFirstResult(start);
			criteria.setMaxResults(end);
			list=criteria.list();
		}
		pagation.setRs(list);
		return pagation;
	}

	@Override
	public void saveOrUpdate(SysUser t) {
		sf.getCurrentSession().saveOrUpdate(t);
		
	}

	@Override
	public void delete(String id) {
		SysUser user=new SysUser();
		user.setAccount(id);
		sf.getCurrentSession().delete(user);
	}

	@Override
	public void delete(String[] ids) {
		StringBuffer sb=new StringBuffer("delete SysUser where id in");
		sb.append("(");
		for(int i=0;i<ids.length;i++){
			sb.append("'");
			sb.append(ids[i]);
			sb.append("'");
			if(i!=ids.length-1){
				sb.append(",");
			}
		}
		sb.append(")");
		sf.getCurrentSession().createQuery(sb.toString()).executeUpdate();
	}

}
